<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div slot="header">
        <span>个人信息</span>
      </div>
      
      <el-form 
        ref="profileForm" 
        :model="profileForm" 
        :rules="rules" 
        label-width="100px">
        <!-- 用户号（不可修改） -->
        <el-form-item label="用户号">
          <el-input v-model="profileForm.userId" disabled></el-input>
        </el-form-item>

        <!-- 角色（不可修改） -->
        <el-form-item label="角色">
          <el-input v-model="profileForm.role" disabled></el-input>
        </el-form-item>

        <!-- 姓名 -->
        <el-form-item label="姓名" prop="name">
          <el-input v-model="profileForm.name"></el-input>
        </el-form-item>

        <!-- 学校信息 -->
        <el-form-item label="学校" prop="universityName">
          <el-input v-model="profileForm.universityName"></el-input>
        </el-form-item>

        <el-form-item label="学院" prop="collegeName">
          <el-input v-model="profileForm.collegeName"></el-input>
        </el-form-item>

        <el-form-item label="专业" prop="majorName">
          <el-input v-model="profileForm.majorName"></el-input>
        </el-form-item>

        <!-- 添加带班信息 -->
        <el-form-item label="带班年级" prop="grade">
          <el-input 
            v-model="profileForm.grade" 
            placeholder="如果您负责带班，请填写带班年级">
          </el-input>
          <div class="form-tip">如果您负责带班，请填写带班年级，否则可以留空</div>
        </el-form-item>

        <el-form-item label="带班班级" prop="classId">
          <el-input 
            v-model="profileForm.classId" 
            placeholder="如果您负责带班，请填写带班班级">
          </el-input>
          <div class="form-tip">如果您负责带班，请填写带班班级，否则可以留空</div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleUpdateProfile" :loading="updating">
            保存修改
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 修改密码表单 -->
      <div class="password-section">
        <h3>修改密码</h3>
        <el-form 
          ref="passwordForm" 
          :model="passwordForm" 
          :rules="passwordRules" 
          label-width="100px">
          <el-form-item label="原密码" prop="oldPassword">
            <el-input 
              v-model="passwordForm.oldPassword" 
              type="password"
              show-password>
            </el-input>
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input 
              v-model="passwordForm.newPassword" 
              type="password"
              show-password>
            </el-input>
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input 
              v-model="passwordForm.confirmPassword" 
              type="password"
              show-password>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleUpdatePassword" :loading="updatingPassword">
              修改密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 注销账号 -->
      <div class="delete-section">
        <h3>注销账号</h3>
        <p class="warning-text">注意：账号注销后将无法恢复，请谨慎操作！</p>
        <el-button type="danger" @click="handleDeleteAccount">
          注销账号
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { userApi } from '@/api'

export default {
  name: 'TeacherProfile',
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      profileForm: {
        userId: '',
        name: '',
        role: '',
        universityName: '',
        collegeName: '',
        majorName: '',
        grade: '',
        classId: ''
      },
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { max: 50, message: '姓名长度不能超过50个字符', trigger: 'blur' }
        ],
        universityName: [
          { required: true, message: '请输入学校名称', trigger: 'blur' }
        ],
        collegeName: [
          { required: true, message: '请输入学院名称', trigger: 'blur' }
        ],
        majorName: [
          { required: true, message: '请输入专业名称', trigger: 'blur' }
        ]
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      updating: false,
      updatingPassword: false
    }
  },
  created() {
    this.fetchUserInfo()
  },
  methods: {
    async fetchUserInfo() {
      try {
        const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
        const res = await userApi.getById(userInfo.userId)
        if (res.code === 200) {
          this.profileForm = res.data
        } else {
          this.$message.error('获取用户信息失败')
        }
      } catch (error) {
        console.error('获取用户信息错误：', error)
        this.$message.error('获取用户信息失败')
      }
    },
    async handleUpdateProfile() {
      try {
        await this.$refs.profileForm.validate()
        this.updating = true
        
        const res = await userApi.update(this.profileForm.userId, this.profileForm)
        if (res.code === 200) {
          this.$message.success('个人信息更新成功')
          // 更新本地存储的用户信息
          localStorage.setItem('user', JSON.stringify(res.data))
        } else {
          this.$message.error(res.message || '更新失败')
        }
      } catch (error) {
        console.error('更新个人信息错误：', error)
        this.$message.error('更新失败，请检查输入信息')
      } finally {
        this.updating = false
      }
    },
    async handleUpdatePassword() {
      try {
        await this.$refs.passwordForm.validate()
        this.updatingPassword = true
        
        const res = await userApi.resetPassword(this.profileForm.userId, {
          oldPassword: this.passwordForm.oldPassword,
          newPassword: this.passwordForm.newPassword
        })
        
        if (res.code === 200) {
          this.$message.success('密码修改成功，请重新登录')
          // 清除登录信息，跳转到登录页
          localStorage.removeItem('user')
          this.$router.push('/admin/login')
        } else {
          this.$message.error(res.message || '密码修改失败')
        }
      } catch (error) {
        console.error('修改密码错误：', error)
        this.$message.error('密码修改失败，请检查输入')
      } finally {
        this.updatingPassword = false
      }
    },
    handleDeleteAccount() {
      this.$confirm('此操作将永久删除您的账号，是否继续？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await userApi.delete(this.profileForm.userId)
          if (res.code === 200) {
            this.$message.success('账号注销成功')
            localStorage.removeItem('user')
            this.$router.push('/admin/login')
          } else {
            this.$message.error(res.message || '注销失败')
          }
        } catch (error) {
          console.error('注销账号错误：', error)
          this.$message.error('注销失败')
        }
      }).catch(() => {
        this.$message.info('已取消注销操作')
      })
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  max-width: 800px;
  margin: 0 auto;
}

.password-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.delete-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.warning-text {
  color: #f56c6c;
  margin-bottom: 15px;
}

h3 {
  margin-bottom: 20px;
  color: #303133;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.2;
}
</style> 